from collections import OrderedDict

from rest_framework.generics import ListCreateAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

from user_app.models import User
from user_app.serializers.user import UserSerializer


class UserList(ListCreateAPIView):
    """
    获取查询用户（查询所有用户详细信息）
    """

    class MyPagination(PageNumberPagination):
        """自定义分页器"""
        page_query_param = 'page'
        page_size_query_param = 'pagesize'

        def get_paginated_response(self, data):
            return Response(OrderedDict([
                ('counts', self.page.paginator.count),  # 获取查询结果总数
                ('lists', data),  # 结果列表
                ('page', self.page.number),  # 当前页码
                ('pages', self.page.paginator.num_pages),  # 总的页码
                ('pagesize',  # 页容量
                 int(self.request.query_params.get(
                     self.page_size_query_param))),

            ]))

    serializer_class = UserSerializer
    queryset = User.objects.all()
    pagination_class = MyPagination

    def get_queryset(self):
        """
        :keyword 存在返回模糊查询结果，否则返回全部结果
        :return:
        """
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return User.objects.filter(username__contains=keyword)
        else:
            return User.objects.all()

    def perform_create(self, serializer):
        """执行创建对象方法"""
        User.objects.create_user(**serializer.validated_data)
